<template>
  <div class="clearfix" style="display: flex;">
    <a-upload
      :action="uploadUrl"
      :headers="headers"
      :name="name"
      :listType="listType"
      :fileList="fileList"
      :multiple="multiple"
      :accept="Accept"
      :showUploadList="showUploadList"
      :beforeUpload="handleBeforeUpload"
      @preview="handlePreview"
      @change="handleChange"
    >
      <div v-if="value.length < maxNum && isPicType">
        <a-icon type="upload"/>
        <div class="ant-upload-text">{{Accept == 'video/*,image/*'?'视频/图片':Accept == 'video/*'?'上传视频':'上传图片'}}</div>
      </div>
      <div v-if="!isPicType">
        <a-button>
          <a-icon type="upload"/>
          上传图片
        </a-button>
      </div>
    </a-upload>
    <!-- <album-lists :defaultValue="value" :isPicType="isPicType" :maxNum="maxNum" @selected="handleSelected"></album-lists> -->
    <a-modal :visible="previewVisible" v-if="previewVisible" :footer="null" @cancel="handleCancel">
      
      <div style="padding: 20px;" v-if="Accept!=='video/*,image/*'">
        <video
          style="width: 100%;height: 100%;"
          v-if="Accept == 'video/*'"
          :src="previewImage"
          controls="controls"
          >
          您的浏览器不支持视频播放
        </video>
        <img v-if="Accept !== 'video/*'" alt="example" style="width: 100%" :src="previewImage"/>
      </div>
      <div style="padding: 20px;" v-else>
        <video
          style="width: 100%;height: 100%;"
          v-if="previewImageType"
          :src="previewImage"
          controls="controls"
          >
          您的浏览器不支持视频播放
        </video>
        <img v-if="!previewImageType" alt="example" style="width: 100%" :src="previewImage"/>
      </div>
    </a-modal>
  </div>
</template>

<script>
import env from '@/config/env';
import { ACCESS_TOKEN,USER_DATA } from '@/store/mutation-types';
// import AlbumLists from '@/components/common/AlbumLists';

export default {
  name: 'Upload',
  components: {
    // AlbumLists,
  },
  props: {
    maxNum: {
      type: Number,
      default: 5,
    },
    value: {
      type:Array,
      default:function(){
        return []
      }
    },
    name: {
      type: String,
      default: 'file',
    },
    Accept: {
      type: String,
      default: 'image/*,.pdf',
    },
    multiple: {
      type: Boolean,
      default: true,
    },
    isPicType: {
      type: Boolean,
      default: true,
    },
    isEditInsert: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      uploadUrl: `${env.baseURL}admin/file.File/add`,
      headers: {
        Accept: 'application/json',
        Authorization: `${this.$ls.get(ACCESS_TOKEN)}`,
        'AdminToken':`${this.$ls.get(ACCESS_TOKEN)}`,
        'X-Requested-With':null
        // 'user-id':`${this.$ls.get(USER_DATA).UserId}`,

      //   config.headers['access-token'] = `${token}`
      // config.headers['user-id'] = `${userid.UserId}`
      // config.headers['market-id'] = `${userid.MarketId}`
      },
      previewVisible: false,
      previewImage: '',
      previewImageType:false, //用来判断图片与视频一起上传时的预览，true为视频格式，false为图片或其他格式
      fileList: [],
      resStep: 0,
      uploadNum: 0,
    };
  },
  computed: {
    listType() {
      if (this.isPicType) {
        return 'picture-card';
      }
      return 'text';
    },
    showUploadList() {
      return this.isPicType;
    },
  },
  watch: {
    value(newVal) {
      this.setDefaultValue(newVal);
    },
  },
  mounted(){
    this.setDefaultValue(this.value);
  },
  methods: {
    setDefaultValue(newVal) {
      if (this.fileList.length === 0) {
        this.fileList = [];
        newVal.forEach((item, index) => {
          const tmp = {
            uid: index,
            name: item.url,
            status: 'done',
            url: item.url,
          };
          this.fileList.push(tmp);
        });
      }
    },
    handleBeforeUpload(file, fileList) {
      this.uploadNum++;
    },
    handleCancel() {
      this.previewVisible = false;
    },
    handlePreview(file) {
      console.log(file,'----');
      this.previewImage = file.url || file.thumbUrl;

      // 判断文件类型格式
      let videoFormat = file.url.split('.').slice(-1)[0]; 
      console.log(videoFormat,'foramt');
      let videoFormatArr = ['mp4','MP4','WebM','webm','Ogg','ogg']; //常用视频格式
      if(videoFormatArr.indexOf(videoFormat) != -1){
        this.previewImageType = true //视频格式
      }else{
        this.previewImageType = false //图片或其他格式
      }

      this.previewVisible = true;
    },
    handleChange(info) {
      let fileList = [...info.fileList];
      fileList = fileList.map((file) => {
        // console.log(fileList);
        if (file.response) {
          if (file.response.code == 200) {
            file.url = file.response.data.file_url;
            file.id = file.response.data.file_id;
          } else {
            file.status = 'error';
          }
        }
        return file;
      });
      // console.log('fileList',fileList);
      this.fileList = fileList;
      this.changeFileList(this.fileList);
    },
    changeFileList(fileList) {
      this.resStep++;
      const pics = [];
      fileList.forEach((item) => {
        // console.log(item);
        if (item.status === 'done') {
          pics.push({url:item.url,id:item.id});
        }
      });
      this.$emit('input', pics);
      // 插入编辑器操作
      if (this.isEditInsert && this.resStep % (3 * this.uploadNum) === 0) {
        this.editInsert(pics);
      }
    },
    handleSelected(pics) {
      pics.forEach((item) => {
        const tmp = {
          uid: parseInt(Math.random() * (99999 - 10000 + 1) + 10000, 10),
          name: item,
          status: 'done',
          url: item,
        };
        this.fileList.push(tmp);
        this.value.push(item);
      });

      // 插入编辑器操作
      if (this.isEditInsert) {
        this.editInsert(pics);
      }
    },
    editInsert(pics) {
      this.$emit('edit-insert', pics);
      this.fileList = [];
    },
  },
};
</script>

<style lang="stylus" scoped>
>>> .ant-upload-select-picture-card i
  font-size: 32px;
  color: #999;

>>> .ant-upload-picture-card-wrapper{
  width: auto;
  display: flex;
}
>>> .ant-upload-select-picture-card .ant-upload-text
  margin-top: 8px;
  color: #666;

>>> .ant-upload-list-item-error
  .ant-upload-list-item-info:before
    content: '上传失败';
    text-align: center;
    background-color: rgba(0, 0, 0, 0.3);
    opacity: 100;

>>> .ant-upload.ant-upload-select-picture-card
  float: left;

>>> .ant-upload.ant-upload-select
  float: left;
</style>
